using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using LeisureCenter.Tools;
using LeisureCenter.LeisureCenterDataSetTableAdapters;

namespace LeisureCenter.LibraryBuilderThreads
{
    public class PathsBrowserThread : SleepingThread
    {
        private Stack<string> paths;
        private List<string> libraryPaths = new List<string>();
        private Object pathsLock = new Object();
        private bool paused = true;
        private FilesCheckerThread filesCheckerThread;
        private int pathsCount;
        private int browsedPathsCount;

        private void BrowsePath(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            try
            {
                if (dir.Name == ".mp3" || dir.Name == "_mp3")
                {
                    return;
                }

                FileSystemInfo[] items = dir.GetFileSystemInfos();
                bool filesFound = false;
                foreach (FileSystemInfo item in items)
                {
                    if (item is FileInfo)
                    {
                        filesCheckerThread.AddFile((FileInfo)item);
                        filesFound = true;
                    }
                    else
                    {
                        paths.Push(item.FullName);
                        pathsCount++;
                    }
                }
                if (filesFound && !filesCheckerThread.Paused)
                {
                    filesCheckerThread.Wakeup();
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                browsedPathsCount++;
            }
        }

        protected override void DoWork()
        {
            paused = false;
            lock (pathsLock)
            {
                paths = new Stack<string>(libraryPaths);
                libraryPaths.Clear();
            }
            while (!paused && paths.Count > 0)
            {
                BrowsePath(paths.Pop());
            }
        }

        public void Pause()
        {
            paused = true;
        }

        public PathsBrowserThread(FilesCheckerThread filesCheckerThread)
        {
            this.filesCheckerThread = filesCheckerThread;
        }

        public void AddPaths(IEnumerable<string> paths)
        {
            lock (pathsLock)
            {
                List<string> newPaths = new List<string>(paths);
                newPaths.Reverse();
                libraryPaths.AddRange(newPaths);
                pathsCount += newPaths.Count;
            }
        }

        public int PathsCount { get { return pathsCount; } }
        public int BrowsedPathsCount { get { return browsedPathsCount; } }
    }
}
